﻿using System;
using TMPro;
using UnityEngine;
using Yoozoo.Gameplay.RTS.Proto;
using Yoozoo.Mars.Got;
using Yoozoo.UI.YGUI;

namespace Yoozoo.Gameplay.RTS
{
    public class CommanderHead : MonoBehaviour
    {
        public Sprite[] BattleLineSprites;
        /// <summary>
        /// 主将头像
        /// </summary>
        public ComCommander MainCommander;

        public Action OnCommanderSwitchEvent;
        
        /// <summary>
        /// 血条和怒气槽
        /// </summary>
        public HpAndRage HpAndRage;

        public YImage BattleLine;
       

        // 战斗箭头组
        //public SpriteRenderer[] battleArrows;

        //public YImage PlaySkillHeroIcon;

        public Transform RightPos;
        public Transform LeftPos;

        public Transform wallHpParent;
        
        public Transform baseArmyInfoParent;
        
        public TMP_Text PlayerName;
        //// 战斗箭头
        //private SpriteRenderer battleArrow;

        //// 战斗名称
        //[SerializeField] private TMP_Text battleName;
        
        private Animator annimator;
        private RectTransform m_rectTransform;

        public CanvasGroup CanvasGroup;
        public RectTransform rectTransform
        {
            get
            {
                if (m_rectTransform == null)
                {
                    m_rectTransform = GetComponent<RectTransform>();
                }
                return m_rectTransform;
            }
        }

        private int soldierCountLevel = -1;
        //控制头像大小随部队数量开关
        private bool isCommanderHeadScale = false;
        public YImage headIconSkill;

        public Collider HeadCollider;
        private int _team = -1;
        private bool _playerNameEnabled;
        internal void SetTouchAble(bool isSelected)
        {
            //HeadCollider.enabled = !isSelected;
        }
        internal void SetBattleLine(int team)
        {
            if (_team!=team)
            {
                BattleLine.sprite = BattleLineSprites[team];
                _team = team;
            }
        }
        public void ShowSkillFocusEffect()
        {
            MainCommander.ShowSkillFocusEffect();
        }

        public void ShowReleaseSkillEffect(int heroId, string skillName, int heroIndex, string heroIcon = null,string monsterSkillIcon = null)
        {
            StopSkillHitEffect();
            if (MainCommander.GetActive())
            {
                headIconSkill.gameObject.SetActive(true);
                if (!string.IsNullOrEmpty(monsterSkillIcon))
                {
                    ArmyManager.Instance.ResourceManager.SetHeroIcon(monsterSkillIcon, headIconSkill);
                }
                else
                {
                    ArmyManager.Instance.ResourceManager.SetHeroIcon(heroIcon, headIconSkill);
                }

                HpAndRage?.ChangeRageStatus(true);
                Timers.inst.Add(2, 1, (o) =>
                 {
                     headIconSkill.gameObject.SetActive(false);
                     PlayCommanderSwitchAni();
                 });
                MainCommander.ShowReleaseSkillEffect(skillName);
                //Debug.LogError("ShowReleaseSkillEffect");
            }
            else
            {
#if DEVELOPMENT_BUILD || UNITY_EDITOR
                Debug.LogError("ShowReleaseSkillEffect null");
#endif
            }
        }

        public void ShowSkillHitEffect()
        {
            MainCommander.ShowSkillHitEffect();
        }

        public void OnDisable()
        {
            Dispose(false);
        }

        public void OnEnabled()
        {
            annimator.ResetTrigger(ani_armyinfo_out);
            annimator.ResetTrigger(ani_sfx_ui_rts_jisha);
        }
        
        public void Dispose(bool deleteHeadIcon)
        {
            CanvasGroup.alpha = 1;
            MainCommander.Dispose(deleteHeadIcon);
            HpAndRage?.Dispose();
            this.annimator.SetTrigger(defaultState);
            //SubCommander.Dispose(deleteHeadIcon);
            ClearAction();
        }

        private bool _battleStyleActive = false;
        private string ani_armyinfo_into = "ani_armyinfo_into";
        private string defaultState = "defaultState";
        private string ani_armyinfo_out = "ani_armyinfo_out";
        private string ani_sfx_ui_rts_jisha = "ani_sfx_ui_rts_jisha";
        private string ani_CommanderHead_Switch = "ani_CommanderHead_qiehuan";
        private bool _isPlayDead = false;
        private bool _isPlayHide = false;
        private Action afterHideAction;
        private Action afterDeadAction;
        private float stateStartTime = 0;
        private float stateDuration;
        public void PlayDefaultState()
        {
            if (!_isPlayDead && !_isPlayHide)
            {
                this.annimator.SetTrigger(defaultState);
            }
        }

        public void PlayShowAni()
        {
            this.annimator.SetTrigger(ani_armyinfo_into);
        }
        public void PlayHideAni(Action action)
        {
            _isPlayHide = true;
            this.annimator.SetTrigger(ani_armyinfo_out);
            stateStartTime = Time.time;
            stateDuration = 0.3f;
            afterHideAction = action;
            /*Timers.inst.Add(0.3f, 1, (obj) =>
            {
                _isPlayHide =false;
                action?.Invoke();
            });*/
        }
        public void PlayDeadAni(Action action)
        {
            _isPlayDead = true;
            this.annimator.SetTrigger(ani_sfx_ui_rts_jisha);
            stateStartTime = Time.time;
            stateDuration = 1;
            afterDeadAction = action;
            /*Timers.inst.Add(1f, 1, (obj) =>
            {
                _isPlayDead = false;
                action?.Invoke();
            });*/
        }

        public void PlayCommanderSwitchAni()
        {
            this.annimator.SetTrigger(ani_CommanderHead_Switch);
        }
        
        /// <summary>
        /// 怒气切换过程中的英雄头像变更
        /// 1. 怒气技能释放前计时2s ChangeRageStatus(true) - 这个阶段怒气槽不能变更
        /// 2. 怒气技能释放结束,进入头像切换阶段              - 走入这个函数,解锁怒气槽锁定,同时变更为当前的英雄头像
        ///     2.1 这个函数是从CommanderHead里的一个动画事件过来的,在那个动画第五帧有一个完全空白的阶段,在这个阶段切换头像
        /// </summary>
        public void OnCommanderSwitch()
        {
            OnCommanderSwitchEvent?.Invoke();
            //ParentHud?.SwitchRageHero();
        }
        
        public void SetGray(bool isGray)
        {
            MainCommander.SetGray(isGray);
        }
        
        public void SetHeadScaleBySoldierCount()
        {
            if (!isCommanderHeadScale)
            {
                return;
            }
            MainCommander.transform.localPosition = new Vector3(0, 0f, 0);
            MainCommander.transform.localScale = new Vector3(1f, 1f, 1f);
        }

        /// <summary>
        /// 统一接口设置头像大小 不要私自设置localscale
        /// </summary>
        /// <param name="scale"></param>
        public void SetScale(float scale)
        {
            transform.localScale = new Vector3(scale, scale, scale);
        }

        public void SetColliderInfo(string info)
        {
            if (HeadCollider)
            {
                HeadCollider.gameObject.name = info;
            }
        }

        public void SetPlayerNameEnable(bool enable)
        {
            if (_playerNameEnabled != enable)
            {
                _playerNameEnabled = enable;
                PlayerName.enabled = enable;
            }
        }

        public void SetPlayerNameTxt(string name)
        {
            if (PlayerName!=null)
            {
                PlayerName.text = name;
            }
        }

        public void SetPlayerNameColor(Color color)
        {
            if (PlayerName!=null)
            {
                PlayerName.color = color;
            }
        }
        private void StopSkillHitEffect()
        {
            MainCommander.StopAnimation();
            //SubCommander.StopAnimation();
            MainCommander.RecoverSkillHitEffect();
        }

        private void Awake()
        {
            var annimator = this.transform.Find("Root").GetComponent<Animator>();
            var changeHeadAni = this.transform.GetComponent<Animation>();
            this.MainCommander.InitAnimation(annimator, changeHeadAni);
            this.annimator = annimator;
            _playerNameEnabled = PlayerName.enabled;
        }

        private void Update()
        {
            if (stateStartTime > 0)
            {
                if (Time.time > stateStartTime + stateDuration)
                {
                    stateStartTime = 0;
                    if (_isPlayDead)
                    {
                        afterDeadAction?.Invoke();
                        afterDeadAction = null;
                        _isPlayDead = false;
                    }
                    else if (_isPlayHide)
                    {
                        afterHideAction?.Invoke();
                        afterHideAction = null;
                        _isPlayHide = false;
                    }
                }
            }
        }

        public void ClearAction()
        {
            ClearDeadAction();
            ClearHideAction();
            stateStartTime = 0;
        }

        public void ClearDeadAction()
        {
            if (_isPlayDead)
            {
                stateStartTime = 0;
            }
            afterDeadAction = null;
            _isPlayDead = false;
        }

        public void ClearHideAction()
        {
            if (_isPlayHide)
            {
                stateStartTime = 0;
            }
            afterHideAction = null;
            _isPlayHide = false;
        }
    }
}
